import { ThunkAction } from 'redux-thunk'
import axios from 'axios'
import { RootState } from '../store'

export const START = 'START' // 正在调用推荐信息api
export const SUCCESS = 'SUCCESS'
export const FAIL = 'FAIL' // 推荐信息api调用失败

interface StartAction {
	type: typeof START
}
interface SuccessAction {
	type: typeof SUCCESS
	payload: any
}
interface FailAction {
	type: typeof FAIL
	payload: any
}
export type AllAction = StartAction | SuccessAction | FailAction

export const startActionCreator = (): StartAction => {
	return {
		type: START
	}
}

export const successActionCreator = (data: any): SuccessAction => {
	return {
		type: SUCCESS,
		payload: data
	}
}
export const failActionCreator = (error: any): FailAction => {
	return {
		type: FAIL,
		payload: error
	}
}

/**
 *  thunk 可以返回一个函数，而不一定是js对象
 *  在一个thunk action中可以完成一些列连续的action操作
 *  并且可以处理异步逻辑
 *  业务逻辑可以从ui层面挪到这里，代码分层会更清晰
 *  参数1 返回函数 定义输出类型
 *  参数2 store state类型
 *  参数3 定义action额外参数
 *  参数4 action类型
 */
export const getTodoList = (): ThunkAction<void, RootState, unknown, AllAction> => async (dispatch, getState) => {
	dispatch(startActionCreator())
	try {
		const res = await axios.get('https://jsonplaceholder.typicode.com/todos')
		dispatch(successActionCreator(res.data))
	} catch (error) {
		dispatch(failActionCreator(error))
	}
}
